_ = require('underscore')
http = require('http')
fs = require('fs')
path = require('path')
cheerio = require('cheerio')
Promise = require("bluebird")
Spider = require('../models/spider')

# writeCsc = (filename, data)->
#   filename ?= path.join(__dirname, 'account.js')
#   fs.writeFile filename, JSON.stringify(data), (err)->
#      if err and typeof(err) is 'string'
#        console.log err
#      else if err and typeof(err) is "object"
#        console.log JSON.stringify(err)
#      console.log("Export Account Success!")

addPage = (url)->
  return new Promise (resolve, reject)->
    console.log('正在爬取', url)
    http.get url, (res)->
      html = ''
      res.on 'data', (data)->
        html += data
      res.on 'end', ()->
        # console.log html
        resolve(html)
      .on 'error', (err)->
        reject err
        console.log "爬取任务出错"

exports.showSpider = (req, res)->
  res.render 'spider', {
    title: 'spider主页'
  }

exports.save = (res, req)->
  console.log(JSON.stringify(req.session.user))
  console.log JSON.stringify(res.body.pageOptions)
  _link = res.body.pageOptions
  # console.log(req.session.user)
  author = "liyang"
  # body = addPage _link.name
  # console.log body
  Spider.findOne {name: _link.name}, (err, spider)->
    console.log err if err
    if spider
      return res.redirect('/spider')
    else
      spider = new Spider {
        url: _link.name,
        author: author,
        meta: {
          createAt:{
            type: Date,
            default: Date.now()
          },
          updateAt: {
            type:Date,
            default: Date.now()
          }
        }
      }
      spider.save (err, spider)->
        console.log err if err
        return res.redirect('/spider')


